import json
import os
from config.constants import TEMP_PATH
#解析allure报告
def parse_allure_json(report_dir):
    """解析 Allure 的 JSON 报告，提取测试结果"""
    test_results = {
        "total": 0,
        "passed": 0,
        "failed": 0,
        "skipped": 0,
        "broken": 0,
        "deselected": 0,  # 新增 deselected 状态统计
        "unknown": 0,  # 新增 unknown 状态统计
    }

    json_files = []
    for root, _, files in os.walk(report_dir):
        for file in files:
            if file.endswith(".json"):
                json_files.append(os.path.join(root, file))

    if not json_files:
        print("❌ 警告：未找到任何 JSON 文件！")
        return test_results

    for file_path in json_files:
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                data = json.load(f)
                status = data.get("status", "") or data.get("state", "")
                if "status" in data or "state" in data:# 兼容不同字段名

                    test_results["total"] += 1
                    if status == "passed":
                        test_results["passed"] += 1
                    elif status == "failed":
                        test_results["failed"] += 1
                    elif status == "skipped":
                        test_results["skipped"] += 1
                    elif status == "broken":
                        test_results["broken"] += 1
                    elif status == "deselected":  # 如果 Allure 报告包含 deselected 状态
                        test_results["deselected"] += 1
                    else:
                        test_results["unknown"] += 1
                        print(f"⚠️ 未知状态: {status}，文件: {file_path}")
        except Exception as e:
            print(f"❌ 解析 JSON 文件失败: {file_path}, 错误: {e}")

    return test_results
# 示例调用
if __name__ == "__main__":
    # report_dir = "./temp/report"
    report_dir = os.path.join(TEMP_PATH, "temp", "report")
    results = parse_allure_json(TEMP_PATH)
    print(f"总用例数:{results['total']}")
    print(f"通过数: {results['passed']}")
    print(f"失败数: {results['failed']}")
    print(f"跳过数: {results['skipped']}")
    print(f"错误数: {results['broken']}")
    print(f"错误数: {results.get('broken')}")